/**
 * ServiceRequestAction.java
 * Created at 2017-11-22
 * Created by zhanghailin
 * Copyright (C) 2017 BROADTEXT SOFTWARE, All rights reserved.
 */
package com.broadtext.rms.system.action;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.broadtext.common.bean.EntityPageBean;
import com.broadtext.common.exp.DaoException;
import com.broadtext.common.exp.ServiceException;
import com.broadtext.common.utils.StringUtils;
import com.broadtext.common.utils.UUIDUtils;
import com.broadtext.rms.basic.service.ITmCustomService;
import com.broadtext.rms.system.model.TmServiceRequest;
import com.broadtext.rms.system.service.IServiceRequestService;
import com.broadtext.rms.system.service.ISysUserService;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;

/**
 * <p>ClassName: ServiceRequestAction</p>
 * <p>Description: TODO</p>
 * <p>Author: zhanghailin</p>
 * <p>Date: 2017-11-22</p>
 */
@Controller
@RequestMapping("/main/serviceRequest")
public class ServiceRequestAction {
    
    /**
     * o 注入客户service
     */
    @Autowired
    @Qualifier("tmCustomService")
    private ITmCustomService tmCustomService;
    
    /**
     * 用户Service
     */
    @Autowired
    @Qualifier("sysUserService")
    private ISysUserService sysUserService;
    
    @Autowired
    @Qualifier("serviceRequestService")
    private IServiceRequestService serviceRequestService;
    
    /**
     * 
     * <p>Description: TODO</p>
     * @param request
     * @param response
     * @return
     * @throws ServiceException
     */
    @RequestMapping(value = "/getServiceRequest.mvc")
    @ResponseBody
    public Map<String,Object> getServiceRequest(HttpServletRequest request, HttpServletResponse response) throws ServiceException {
        PageBounds pageBounds = new PageBounds();
        //解析请求参数，将String字符串转为map
        Map<String,Object> map = new HashMap<String,Object>();
        String aoData = request.getParameter("aoData");
        JSONArray array = JSONArray.parseArray(aoData);
        if (array!=null) {
            Iterator<Object> it = array.iterator();
            while (it.hasNext()) {
                JSONObject obj;
                obj = (JSONObject) it.next();
                if (obj.get("value") != null && StringUtils.isNotBlank(obj.get("value")+"")) {
                    map.put(obj.get("name") + "", obj.get("value"));
                }
            }
        }
        //判断登录账户类型，如果为客户账户则过滤数据，客户类型只看本级和本下级
        Map<String, Object> checkMap;
        List<String> list;
        try {
            checkMap = this.sysUserService.checkUserClass(request.getSession().getAttribute("sys.user").toString());
            if(null != checkMap && "true".equals(checkMap.get("flag").toString())){
                //该用户是客户账号
                map.put("cusId", checkMap.get("cusId"));
                //查询当前登录用户所有下属子节点pk_id
                list = this.tmCustomService.getChildCusIdArray(checkMap.get("cusId")+"");
                map.put("ids", list);
            }
        } catch (DaoException e1) {
            e1.printStackTrace();
        }
        //分页查询条数
        pageBounds.setLimit(Integer.parseInt(map.get("iDisplayLength").toString()));
        //分页第几页
        pageBounds.setPage(Integer.parseInt(map.get("iDisplayStart").toString()) / pageBounds.getLimit() + 1);
        Map<String, Object> dataMap = new HashMap<String, Object>();
        try {
            EntityPageBean<TmServiceRequest> pageBean = this.serviceRequestService.findEntityPageByQuery(map, pageBounds);
            dataMap.put("recordsTotal", pageBean.getiTotalRecords());
            dataMap.put("recordsFiltered", pageBean.getiTotalRecords());
            dataMap.put("aaData", pageBean.getResults());
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return dataMap;
    }
    
    /**
     * 
     * <p>Description: TODO</p>
     * @param request
     * @param response
     * @param TmCustomAlert
     * @return
     * @throws ServiceException
     */
    @RequestMapping(value = "/saveOrUpdateserviceRequest.mvc")
    @ResponseBody
    public Map<String, Object> saveOrUpdateserviceRequest(HttpServletRequest request, HttpServletResponse response,TmServiceRequest t) throws ServiceException {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        String currentUser = String.valueOf(request.getSession().getAttribute("sys.userName"));
        if(StringUtils.isBlank(currentUser)||"null".equals(currentUser)){
            currentUser = t.getCurrentUser();
        }
        t.setDelFlag("0");
        t.setUpdateUser(currentUser);
        t.setUpdateDate(new Date());
        try{
            //if (!"".equals(t.getPkId())) {
            if(StringUtils.isNotBlank(t.getPkId())){
                //编辑
                t.setUpdateUser(currentUser);
                t.setUpdateDate(new Date());
                this.serviceRequestService.updateRecord(t);
            } else {
                //新增
                //初始化服务计划状态 1 未处理 2 已确认 3处理中 4 已解决 5 已关闭
                t.setRequestStartDate(new Date());
                t.setRequestStatus("1");
                t.setCreateUser(currentUser);
                t.setCreateDate(new Date());
                t.setPkId(UUIDUtils.getUUID());
                this.serviceRequestService.saveServiceReq(t);
            }
            dataMap.put("msg", "SUCCESS");
        } catch (ServiceException e) {
            dataMap.put("msg", "FAILURE");
            e.printStackTrace();
        } 
        return dataMap;
    }
    
    
    /**
     * 
     * <p>Description: TODO</p>
     * @param pkId
     * @return
     * @throws ServiceException 
     */
    @RequestMapping(value="/getReqById.mvc")
    @ResponseBody
    public TmServiceRequest getReqById(String pkId) throws ServiceException {
        TmServiceRequest t = new TmServiceRequest();
        t = this.serviceRequestService.getReqById(pkId);
        return t;
    }
    
    /**
     * <p>
     * Description: 删除
     * </p>
     * 
     * @param request 请求
     * @param pkId id
     * @param response 返回对象
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping(value = "/deleteServiceReq.mvc")
    @ResponseBody
    public Object delete(HttpServletRequest request, String pkId, HttpServletResponse response) {
        //返回成功
        Map dataMap;
        dataMap = new HashMap();
        //数组 存储待删除主键id
        String[] idArray;
        idArray = pkId.split(",");
        try {
            this.serviceRequestService.deleteServiceRequest(idArray, String.valueOf(request.getSession().getAttribute("sys.userName")));
            dataMap.put("msg", "SUCCESS");
        } catch (ServiceException e) {
            dataMap.put("msg", "FAILURE");
            e.printStackTrace();
        }
        return dataMap;
    }
    
    /**
     * 
     * <p>
     * Description: 检查请求编码是否重复
     * </p>
     * 
     * @param requestCode
     * @param pkId
     * @return Map<String, Object>
     * @throws ServiceException 异常
     */
    @RequestMapping(value = "/checkRepeatReqCode.mvc")
    @ResponseBody
    public Map<String, Object>  checkRepeatReqCode(String requestCode, String pkId) throws ServiceException {
        Map<String, Object> map = new HashMap<String, Object>();
        Boolean flag = this.serviceRequestService.checkRepeatReqCode(requestCode, pkId);
        if(flag){
            map.put("msg", true);
        }else {
            map.put("msg", false);
        }
        return map;
    }


}
